from fastapi import APIRouter
from starlette.requests import Request

from base.bean.beans import ApiFlowBean, ApiCommonBean
from base.util.api_util import ApiUtil
from capture_api import  get_current_config_
from global_ver import flowDao

flowRouter = APIRouter()


@flowRouter.post('/get_flow_list',description="获取流列表")
def get_flow_list():
    return ApiUtil.wrap_correct(flowDao.get_flow_list())


@flowRouter.post('/run_flow',description="运行流程")
def run_flow(bean: ApiFlowBean, request: Request):
    flow = flowDao.get_flow_by_id(bean.flow_id)
    if flow is None:
        return ApiUtil.wrap_error("没找到这个流程")
    config = get_current_config_()
    if config.catalogue is None or config.catalogue == '':
        config.catalogue = ApiUtil.get_default_catalogue()
    print(f"splitNumber:{config.splitNumber}")
    request.app.state.threadManager.start_thread(ApiUtil.background_task_flow, flow,
                                                 config,
                                                 request.app.state.base_config,
                                                 request.app.state.redisUtil,
                                                 request.app.state.geoUtil,
                                                 request.app.state.esdb
                                                 )
    return ApiUtil.wrap_correct(f"已开始运行流程：{bean.flow_id}")


@flowRouter.post('/update_flow',description="更新流程")
def add_flow(bean: ApiFlowBean):
    flowDao.add_flow(description=bean.description, step=bean.step, flow_id=bean.id)
    return ApiUtil.wrap_correct(f"添加成功")


@flowRouter.post('/delete_flow',description="删除流程")
def delete_flow(bean: ApiCommonBean):
    flowDao.delete_by_id(bean.id)
    return ApiUtil.wrap_correct(f"删除成功")


@flowRouter.post('/get_flow_by_id',description="通过id获取流程")
def get_flow_info(bean: ApiCommonBean):
    return ApiUtil.wrap_correct(flowDao.get_flow_by_id(bean.id))
